package stub

import "sync"

var (
	srvInstanceID uint32 = 1
)

type StubBox struct {
	index   int           //序号，用于随机返回理论上应该这里是只有一个实例的
	srvlist []*ServerStub //服务列表
}

type StubManager struct {
	boxs   map[uint64]*StubBox    //SrvStub 实例管理
	stubs  map[uint32]*ServerStub //实例id - 实例的存储用于快速索引
	rwlock sync.RWMutex           //读写
}

func NewServerStubMgr() *StubManager {
	stubmgr := &StubManager{
		boxs:  make(map[uint64]*StubBox),
		stubs: make(map[uint32]*ServerStub),
	}
	return stubmgr
}

//只有主协程访问
func (stubmgr *StubManager) AddService(srvStub *ServerStub) *ServerStub {
	if srvStub == nil {
		//TODO add some log
		return nil
	}

	box, ok := stubmgr.boxs[srvStub.servuuid]
	if !ok {
		box = &StubBox{
			index: 0,
		}
		stubmgr.boxs[srvStub.servuuid] = box
	}

	box.srvlist = append(box.srvlist, srvStub)

	srvStub.servid = srvInstanceID
	srvInstanceID++
	stubmgr.stubs[srvStub.servid] = srvStub

	srvStub.onLoad()

	return srvStub
}

//@title 获取service的stub
func (stubmgr *StubManager) GetService(uuid uint64, srvID uint32) *ServerStub {
	if stubmgr == nil {
		return nil
	}
	if srvID != 0 {
		v, ok := stubmgr.stubs[srvID]
		if !ok {
			return nil
		} else {
			return v
		}
	} else {
		box, ok := stubmgr.boxs[uuid]
		if !ok {
			return nil
		} else {
			if len(box.srvlist) == 0 {
				return nil
			} else if box.index >= len(box.srvlist) {
				box.index = 0
			}
			stub := box.srvlist[box.index]
			box.index++
			return stub
		}
	}
}

func (stub *StubManager) Tick() {
	for _, v := range stub.stubs {
		//TODO add status Refresh
		v.Tick()
	}
}

func (stub *StubManager) Start() {
	for _, v := range stub.stubs {
		v.StartLoop()
	}
}
